package com.xw.echo.core.cluster;

import com.xw.echo.core.register.HostAndPort;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class RoundRobinLoadBalance implements LoadBalancer{

    private final AtomicInteger index = new AtomicInteger(0);

    @Override
    public String select(List<HostAndPort> hostAndPorts) {
        if (hostAndPorts == null || hostAndPorts.isEmpty()) {
            return null; // 或者抛出异常，取决于你的错误处理策略
        }
        int currentIndex = index.getAndIncrement();
        int nextIndex = Math.abs(currentIndex % hostAndPorts.size()); // 使用绝对值防止负数
        HostAndPort selectedHost = hostAndPorts.get(nextIndex);
        return selectedHost.getHost() + ":" + selectedHost.getPort();

    }

}
